import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import './style/publish.css';
import { useNavigate } from 'react-router-dom';

const Camera = () => {
  const [stream, setStream] = useState(null);
  const [isCameraOn, setIsCameraOn] = useState(false);
  const [capturedImage, setCapturedImage] = useState(null); // 存储捕获的图片URL
  const [capturedVideo, setCapturedVideo] = useState(null); // 存储录制的视频URL
  const [uploading, setUploading] = useState(false); // 上传状态
  const [error, setError] = useState(null); // 错误信息
  const videoRef = useRef(null);
  const mediaRecorderRef = useRef(null);
  const recordedChunksRef = useRef([]);
  const navigate = useNavigate();
  const [flagShi, setFlagShi] = useState(localStorage.getItem('setFlagShi') || 1);
  const [flag, setFlag] = useState(localStorage.getItem('flag') || 1);

  // 请求访问用户媒体设备
  const startCamera = async () => {
    try {
      console.log('Trying to get user media...');
      const newStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" }, audio: true });
      console.log('Got user media stream:', newStream);
      setStream(newStream);
      if (videoRef.current) {
        videoRef.current.srcObject = newStream;
        console.log('Set srcObject to video element.');
      }
      setIsCameraOn(true); // 摄像头已启动
    } catch (error) {
      console.error("Error accessing media devices.", error);
      setError('无法访问摄像头，请检查权限设置。');
    }
  };

  // 开始录制
  const startRecording = () => {
    setFlagShi(2);
    if (stream) {
      const options = { mimeType: 'video/webm; codecs=vp9' };
      const mediaRecorder = new MediaRecorder(stream, options);

      mediaRecorderRef.current = mediaRecorder;
      recordedChunksRef.current = [];

      mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          recordedChunksRef.current.push(event.data);
        }
      };

      mediaRecorder.onstop = () => {
        const blob = new Blob(recordedChunksRef.current, { type: 'video/webm' });
        const url = URL.createObjectURL(blob);
        setCapturedVideo(url);
        uploadVideo(blob); // 上传录制的视频
      };

      mediaRecorder.start();
    }
  };

  // 停止录制
  const stopRecording = () => {
    setFlagShi(1);
    if (mediaRecorderRef.current) {
      mediaRecorderRef.current.stop();
    }
  };

  // 拍照
  const takePhoto = () => {
    if (videoRef.current) {
      const canvas = document.createElement('canvas');
      canvas.width = videoRef.current.videoWidth;
      canvas.height = videoRef.current.videoHeight;
      const context = canvas.getContext('2d');

      context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);

      // 直接将 canvas 内容转换为 Blob
      canvas.toBlob((blob) => {
        if (blob) {
          const file = new File([blob], 'captured_image.png', { type: 'image/png' });

          // 创建 FormData 并附加文件
          const formData = new FormData();
          formData.append('file', file); // 注意：这里的 key 是 'file'，因为后端期望的是 'file'

          // 上传图片到后端
          uploadImage(formData);
        } else {
          console.error('Failed to create Blob from canvas.');
        }
      }, 'image/png');

      // 将 canvas 内容显示为图片
      const imageDataURL = canvas.toDataURL('image/png');
      setCapturedImage(imageDataURL);
    }
  };

  // 上传图片到后端
  const uploadImage = async (formData) => {
    setUploading(true);
    try {
      const response = await axios.post('http://localhost:3000/yjr/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      const uploadedImageUrl = response.data.path; // 后端返回的图片路径
      setCapturedImage(uploadedImageUrl); // 更新状态以显示上传后的图片
      const uploaddd = uploadedImageUrl.split('\\');
      console.log(uploaddd);

      localStorage.setItem('image', uploaddd[0] + '/' + uploaddd[1]);
      setTimeout(() => {
        navigate('/videoImg');
      }, 100);
    } catch (error) {
      console.error('Error uploading image:', error);
      setError('无法上传图片，请稍后再试。');
    } finally {
      setUploading(false);
    }
  };

  // 上传视频到后端
  const uploadVideo = async (blob) => {
    setUploading(true);
    try {
      const file = new File([blob], 'captured_video.webm', { type: 'video/webm' });
      const formData = new FormData();
      formData.append('file', file); // 注意：这里的 key 是 'file'，因为后端期望的是 'file'

      const response = await axios.post('http://localhost:3000/yjr/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      const uploadedVideoUrl = response.data.path; // 后端返回的视频路径
      setCapturedVideo(uploadedVideoUrl); // 更新状态以显示上传后的视频
      const uploaddd = uploadedVideoUrl.split('\\');
      console.log(uploaddd);

      localStorage.setItem('image', uploaddd[0] + '/' + uploaddd[1]);
      setTimeout(() => {
        navigate('/videoImg');
      }, 100);
    } catch (error) {
      console.error('Error uploading video:', error);
      setError('无法上传视频，请稍后再试。');
    } finally {
      setUploading(false);
    }
  };

  // 页面加载时自动启动摄像头
  useEffect(() => {
    startCamera();

    // 清理流以避免内存泄漏
    return () => {
      if (stream) {
        stream.getTracks().forEach((track) => track.stop());
        setStream(null);
      }
    };
  }, []); // 空依赖数组确保只执行一次

  // 检查是否支持 getUserMedia 和 MediaRecorder
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia || !window.MediaRecorder) {
    return <p>当前浏览器不支持摄像头访问或视频录制。</p>;
  }

  const handlePai = () => {
    setFlag(1);
    localStorage.setItem('flag', 1);
  };

  const handleShi = () => {
    setFlag(2);
    localStorage.setItem('flag', 2);
  };

  return (
    <div className="publishBox">
      {/* {isCameraOn && ( */}
        <>
          <video
            ref={videoRef}
            autoPlay
            muted
            playsInline
            style={{
              position: 'fixed',
              top: 0,
              left: 0,
              width: '100vw',
              height: '100vh',
              objectFit: 'cover',
              zIndex: -1,
              border: 'none'
            }}
          />
          <div>
            <h2 className={`paishi1 ${localStorage.getItem('flag') == 1 ? 'bai' : ''}`} onClick={handlePai}>
              拍照
            </h2>
            <h2 className={`paishi2 ${localStorage.getItem('flag') == 2 ? 'bai' : ''}`} onClick={handleShi}>
              视频
            </h2>

            {flag == 1 ? (
              <div className="pai-div">
                <button onClick={takePhoto} className="pai"></button>
              </div>
            ) : null}

            <div>
              {flag == 2 ? (
                <div>
                  {flagShi == 1 ? (
                    <div>
                      <div className="pai-div">
                        <button onClick={startRecording} className="shi"></button>
                      </div>
                    </div>
                  ) : (
                    <div className="hui1">
                      <div className="hui2">
                        <button onClick={stopRecording} className="smallShi"></button>
                      </div>
                    </div>
                  )}
                </div>
              ) : null}
            </div>
          </div>
        </>
      {/* )} */}
      {error && <p className="error">{error}</p>}
      {uploading && <p>上传中...</p>}
    </div>
  );
};

export default Camera;